﻿using Prism.Commands;
using Prism.Mvvm;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using Microsoft.Win32;
using OfficeOpenXml;
using System.IO;
using System.Windows;
using BaseMod.Models;

namespace BaseMod.ViewModels
{
    public class BaseWindowViewModel : BindableBase
    {
        public string Title { get; set; } = "Base";
        public DelegateCommand TestMakOperaCommand { get; set; }
        public DelegateCommand OpenElsxFileCommand { get; set; }
        public DelegateCommand TestMenoryImageCommand { get; set; }
        public BaseWindowViewModel()
        {
            OpenElsxFileCommand = new DelegateCommand(OnOpenElsxFile);
            TestMakOperaCommand = new DelegateCommand(OnTestMakOpera);
            TestMenoryImageCommand = new DelegateCommand(OnTestMenoryImage);
        }

   

        private void OnTestMakOpera()
        {
            var ofd = new OpenFileDialog();
            ofd.Filter = "Vid文件|*.vid";
            ofd.Multiselect = false;
            
            List<ushort> dataList = new List<ushort>();
            var outputPath = $"{DateTime.Now.ToString("yyyyMMdd.hhmmss")}.out.png";
            if (ofd.ShowDialog() == true)
            {
                BinaryReader br = new BinaryReader(File.Open(ofd.FileName, FileMode.Open));
                //IMagickColor<ushort> input = new MagickColor();
                for (int i = 0; i < 3600 * 3080; i++)
                {
                    var r = br.ReadUInt16();
                    var _r =(byte)( r & 0xFF);
                    dataList.Add(_r);
                }
            }
            //    var width = 3600;
            //var height = 3080;
            //ushort[] data = dataList.ToArray();
            //using var image = new MagickImage(MagickColors.Transparent,width,height);

            //using var pixels = image.GetPixels();
            //pixels.SetArea(0, 0, width, height, data);
            
            //image.Write(outputPath, MagickFormat.Png);
        }

        private void OnOpenElsxFile()
        {
            var ofd = new OpenFileDialog();
            ofd.Filter = "Excel 文件|*.xlsx";
            ofd.Multiselect = false;
            if (ofd.ShowDialog() == true)
            {
                var fileName = ofd.FileName;
                using (var package = new ExcelPackage(new FileInfo(fileName)))
                {
                    var sheets = package.Workbook.Worksheets;
                    foreach (var sheet in sheets)
                    {
                        var sheetName= sheet.Name;

                        var rowStart = sheet.Dimension.Start.Row;  
                        var colStart = sheet.Dimension.Start.Column;
                        var rowEnd = sheet.Dimension.End.Row;
                        var colEnd = sheet.Dimension.End.Column;


                        var colNames = "";
                        var colDatas = "";

                        DbOperaType currentDbOperaType = DbOperaType.Insert;
                        //header row index
                        int headerRow = 0;
                        int idCol = 0;

                        for (int i = rowStart; i <= rowEnd; i++)
                        {
                            for (int j = colStart; j <= colEnd; j++)
                            {
                                var itemValue = sheet.Cells[i,j].Value;
                                if (itemValue != null)
                                {
                                    if (itemValue.ToString().ToLower() == "header")
                                    {

                                        headerRow = i;
                                        continue;
                                    }
                                }
                                if (headerRow == i)
                                {
                                    if (currentDbOperaType == DbOperaType.Insert)
                                    {
                                        if (itemValue.ToString().ToLower() == "id")
                                        {
                                            idCol = j;
                                            continue;
                                        }
                                        else
                                        {
                                            colNames += itemValue.ToString() + ",";
                                            continue;
                                        }
                                    }
                                }

                                if (j == 1)
                                {
                                    if (itemValue != null)
                                    {
                                        if (itemValue.ToString().ToLower() == "a")
                                        {
                                            currentDbOperaType = DbOperaType.Insert;
                                            continue;
                                        }
                                        else if (itemValue.ToString().ToLower() == "m")
                                        {
                                            currentDbOperaType = DbOperaType.Modify; 
                                            continue;
                                        }
                                        else if (itemValue.ToString().ToLower() == "d")
                                        {
                                            currentDbOperaType = DbOperaType.Delete; 
                                            continue;
                                        }
                                        else
                                        {
                                            return;
                                        }
                                    }
                                }
                                else
                                {
                                    if (currentDbOperaType == DbOperaType.Insert)
                                    {
                                        if (idCol != j)
                                        {
                                            if (itemValue != null)
                                                colDatas += "'" + itemValue.ToString()+"'" + ",";
                                            else
                                                colDatas += "' '" + ",";
                                        }
                                    }
                                }

                                if (currentDbOperaType == DbOperaType.Insert && j == colEnd)
                                {
                                    var insertSql =
                                        $"Insert into {sheetName} ({colNames.Substring(0, colNames.Length - 1)}) valus ({colDatas.Substring(0, colDatas.Length - 1)});";
                                    MessageBox.Show(insertSql);
                                }
                            }
                        }
                    }
                }
            }
        }


        //////////////////////////////////////////////////
        ///
        private string curFileName;//文件路径
        private Bitmap curBitmap;//图像对象
        private void OnTestMenoryImage()
        {
            var ofd = new OpenFileDialog();
            ofd.Filter = "Vid文件|*.vid";
            ofd.Multiselect = false;

            List<ushort> dataList = new List<ushort>();
            var outputPath = $"{DateTime.Now.ToString("yyyyMMdd.hhmmss")}.out.png";
            if (ofd.ShowDialog() == true)
            {
                BinaryReader br = new BinaryReader(File.Open(ofd.FileName, FileMode.Open));
                //IMagickColor<ushort> input = new MagickColor();
                for (int i = 0; i < 3600 * 3080; i++)
                {
                    var r = br.ReadUInt16();
                    var _r = (byte)(r & 0xFF);
                    dataList.Add(_r);
                }
            }
            var width = 3600;
            var height = 3080;
            ushort[] data = dataList.ToArray();
            //using var image = new MagickImage(MagickColors.Transparent, width, height);

            //using var pixels = image.GetPixels();
            //pixels.SetArea(0, 0, width, height, data);

            //curBitmap = image.ToBitmap(ImageFormat.Png);
        }

        public void RefreshBitmap()
        {
            if (curBitmap != null)
            {

                Rectangle rect = new Rectangle(0, 0, curBitmap.Width, curBitmap.Height);//新建矩形绘板
                System.Drawing.Imaging.BitmapData bmpData = curBitmap.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite, curBitmap.PixelFormat);
                IntPtr ptr = bmpData.Scan0;
                int bytes = curBitmap.Width * curBitmap.Height * 3;
                byte[] rgbValues = new byte[bytes];
                System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, bytes); //将intPtr变量ptr(非托管对象）复制到一维的字节数组rgbValues（托管对象）中
                double colorTemp = 0;
                for (int i = 0; i < rgbValues.Length; i += 3)
                {
                    colorTemp = rgbValues[i + 2] * 0.299 + rgbValues[i + 1] * 0.587 + rgbValues[i] * 0.114;
                    rgbValues[i] = rgbValues[i + 1] = rgbValues[i + 2] = (byte)colorTemp;

                }
                System.Runtime.InteropServices.Marshal.Copy(rgbValues, 0, ptr, bytes);//将一维的字节数组rgbValues（托管对象）复制到intPtr变量ptr(非托管对象）中
                curBitmap.UnlockBits(bmpData);


            }
        }
    }
}
